using System.Text;
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;

namespace BlazeApps.Library.Messaging
{
    [Serializable()]
    public class PrivateMessage : Csla.BusinessBase<PrivateMessage>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _privatemessageid = Guid.NewGuid();
        private Guid _fromuserid = Guid.NewGuid();
        private string _subject = string.Empty;
        private string _body = string.Empty;
        private SmartDate _createdate = new SmartDate(DateTime.Now);
        private Guid _userprivatemessageid = Guid.NewGuid();
        private Guid _userid = Guid.NewGuid();
        private bool _isviewed = false;
        private string _fromusername = string.Empty;

        [System.ComponentModel.DataObjectField(true, true)]
        public Guid privatemessageid
        {
            get
            {
                CanReadProperty("privatemessageid", true);
                return _privatemessageid;
            }
        }

        public Guid fromuserid
        {
            get
            {
                CanReadProperty("fromuserid", true);
                return _fromuserid;
            }
            set
            {
                CanWriteProperty("fromuserid", true);
                if (!_fromuserid.Equals(value))
                {
                    _fromuserid = value;
                    PropertyHasChanged("fromuserid");
                }
            }
        }

        public string subject
        {
            get
            {
                CanReadProperty("subject", true);
                return _subject;
            }
            set
            {
                CanWriteProperty("subject", true);
                if (value == null)
                    value = string.Empty;
                if (!_subject.Equals(value))
                {
                    _subject = value;
                    PropertyHasChanged("subject");
                }
            }
        }

        public string body
        {
            get
            {
                CanReadProperty("body", true);
                return _body;
            }
            set
            {
                CanWriteProperty("body", true);
                if (value == null)
                    value = string.Empty;
                if (!_body.Equals(value))
                {
                    _body = value;
                    PropertyHasChanged("body");
                }
            }
        }

        public DateTime createdate
        {
            get
            {
                CanReadProperty("createdate", true);
                return _createdate.Date;
            }
        }

        public string createdateString
        {
            get
            {
                CanReadProperty("createdate", true);
                return _createdate.Text;
            }
            set
            {
                CanWriteProperty("createdate", true);
                if (value == null)
                    value = string.Empty;
                if (!_createdate.Equals(value))
                {
                    _createdate.Text = value;
                    PropertyHasChanged("createdate");
                }
            }
        }

        public Guid userprivatemessageid
        {
            get
            {
                CanReadProperty("userprivatemessageid", true);
                return _userprivatemessageid;
            }
        }

        public Guid userid
        {
            get
            {
                CanReadProperty("userid", true);
                return _userid;
            }
            set
            {
                CanWriteProperty("userid", true);
                if (!_userid.Equals(value))
                {
                    _userid = value;
                    PropertyHasChanged("userid");
                }
            }
        }

        public bool isviewed
        {
            get
            {
                CanReadProperty("isviewed", true);
                return _isviewed;
            }
            set
            {
                CanWriteProperty("isviewed", true);
                if (!_isviewed.Equals(value))
                {
                    _isviewed = value;
                    PropertyHasChanged("isviewed");
                }
            }
        }

        public string fromusername
        {
            get
            {
                CanReadProperty("fromusername", true);
                return _fromusername;
            }
        }

        protected override object GetIdValue()
        {
            return _privatemessageid;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // subject
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "subject");
            //
            // body
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "body");
            //
            // createdate
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "createdateString");
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in PrivateMessage
            //AuthorizationRules.AllowRead("privatemessageid", "PrivateMessageReadGroup");
            //AuthorizationRules.AllowRead("fromuserid", "PrivateMessageReadGroup");
            //AuthorizationRules.AllowRead("subject", "PrivateMessageReadGroup");
            //AuthorizationRules.AllowRead("body", "PrivateMessageReadGroup");
            //AuthorizationRules.AllowRead("createdate", "PrivateMessageReadGroup");
            //AuthorizationRules.AllowRead("userprivatemessageid", "PrivateMessageReadGroup");
            //AuthorizationRules.AllowRead("userid", "PrivateMessageReadGroup");
            //AuthorizationRules.AllowRead("isviewed", "PrivateMessageReadGroup");

            //AuthorizationRules.AllowWrite("subject", "PrivateMessageWriteGroup");
            //AuthorizationRules.AllowWrite("body", "PrivateMessageWriteGroup");
            //AuthorizationRules.AllowWrite("createdate", "PrivateMessageWriteGroup");
            //AuthorizationRules.AllowWrite("isviewed", "PrivateMessageWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in PrivateMessage
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PrivateMessageViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in PrivateMessage
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PrivateMessageAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in PrivateMessage
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PrivateMessageEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in PrivateMessage
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PrivateMessageDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private PrivateMessage()
        { /* require use of factory method */
        }

        public static PrivateMessage NewPrivateMessage()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a PrivateMessage");
            return DataPortal.Create<PrivateMessage>();
        }

        public static PrivateMessage GetPrivateMessage(Guid privatemessageid)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a PrivateMessage");
            return DataPortal.Fetch<PrivateMessage>(new Criteria(privatemessageid));
        }

        public static void DeletePrivateMessage(Guid privatemessageid)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a PrivateMessage");
            DataPortal.Delete(new Criteria(privatemessageid));
        }

        public override PrivateMessage Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a PrivateMessage");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a PrivateMessage");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a PrivateMessage");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid privatemessageid;

            public Criteria(Guid privatemessageid)
            {
                this.privatemessageid = privatemessageid;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
         protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@privatemessageid", criteria.privatemessageid);

            using(SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetMessageByMessageID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            _privatemessageid = dr.GetGuid("privatemessageid");
            _fromuserid = dr.GetGuid("fromuserid");
            _subject = dr.GetString("subject");
            _body = dr.GetString("body");
            _createdate = dr.GetSmartDate("createdate", _createdate.EmptyIsMin);
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }

        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertMessage.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@privatemessageid", _privatemessageid);
            DAL.AddParameter("@FromUserID", _fromuserid);
            DAL.AddParameter("@Subject", _subject);
            DAL.AddParameter("@Body", _body);
            DAL.AddParameter("@UserPrivateMessageID", _userprivatemessageid);
            DAL.AddParameter("@UserID", _userid);
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        //protected override void DataPortal_Update()
        //{
        //    if (base.IsDirty)
        //    {
        //        ExecuteUpdate();
        //    }
        //}

        //private void ExecuteUpdate()
        //{
        //    DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

        //    AddUpdateParameters(ref DAL);

        //    DAL.ExecuteNonQuery("usp_update_page", CommandType.StoredProcedure, ConnectionState.Open);
        //}

        //private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        //{
        //    //cm.Parameters.AddWithValue("@privatemessageid", _privatemessageid);
        //    //cm.Parameters.AddWithValue("@fromuserid", _fromuserid);
        //    //cm.Parameters.AddWithValue("@subject", _subject);
        //    //cm.Parameters.AddWithValue("@body", _body);
        //    //cm.Parameters.AddWithValue("@createdate", _createdate.DBValue);
        //    //cm.Parameters.AddWithValue("@userprivatemessageid", _userprivatemessageid);
        //    //cm.Parameters.AddWithValue("@userid", _userid);
        //    //cm.Parameters.AddWithValue("@isviewed", _isviewed);
        //}

        //private void UpdateChildren(SqlConnection cn)
        //{
        //}
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_privatemessageid));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery(Procs.DeleteMessage.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@privatemessageid", criteria.privatemessageid);         
        }
        #endregion //Data Access - Delete

        #endregion //Data Access
    }
}
